<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>南开大学搜索引擎</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #fff;
            color: #333;
        }
        .container {
            width: 100%;
            max-width: 100%;
            padding: 0;
        }
        .header {
            display: flex;
            justify-content: flex-end;
            padding: 20px 30px 0 0;
        }
        .header a {
            color: #333;
            text-decoration: none;
            margin-left: 20px;
            font-size: 14px;
        }
        .header a:hover {
            color: #5E2D9B;
        }
        .search-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-top: 100px;
        }
        .logo {
            margin-bottom: 30px;
            text-align: center;
        }
        .logo h1 {
            font-size: 42px;
            color: #5E2D9B;
            margin: 0;
        }
        .search-form-container {
            width: 100%;
            max-width: 650px;
            position: relative;
        }
        .search-form {
            width: 100%;
            display: flex;
            position: relative;
            border: 2px solid #5E2D9B;
            border-radius: 24px;
            overflow: hidden;
        }
        .search-input {
            flex: 1;
            padding: 15px 20px;
            font-size: 16px;
            border: none;
            outline: none;
            width: 100%;
        }
        .search-button {
            background-color: #5E2D9B;
            color: white;
            border: none;
            padding: 0 30px;
            cursor: pointer;
            font-size: 16px;
            white-space: nowrap;
        }
        .search-button:hover {
            background-color: #4A2379;
        }
        .search-tabs {
            margin-top: 20px;
            display: flex;
            gap: 20px;
        }
        .search-option {
            display: flex;
            align-items: center;
            gap: 5px;
            cursor: pointer;
        }
        .search-option input {
            cursor: pointer;
        }
        .search-option label {
            cursor: pointer;
            font-size: 14px;
        }
        .history-container {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 1px solid #ddd;
            border-radius: 0 0 8px 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            z-index: 100;
            max-height: 300px;
            overflow-y: auto;
            display: none;
        }
        .history-item {
            padding: 10px 15px;
            cursor: pointer;
            border-bottom: 1px solid #eee;
        }
        .history-item:hover {
            background: #f5f5f5;
        }
        .history-item:last-child {
            border-bottom: none;
        }
        .results-container {
            padding: 20px;
            max-width: 750px;
            margin: 20px auto;
        }
        .result-item {
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }
        .result-item:last-child {
            border-bottom: none;
        }
        .result-title {
            font-size: 18px;
            margin-bottom: 5px;
        }
        .result-title a {
            color: #1a0dab;
            text-decoration: none;
            font-weight: normal;
        }
        .result-title a:hover {
            text-decoration: underline;
        }
        .result-url {
            color: #006621;
            font-size: 14px;
            margin-bottom: 5px;
        }
        .result-snippet {
            color: #545454;
            font-size: 14px;
            line-height: 1.4;
        }
        .result-meta {
            color: #777;
            font-size: 13px;
            margin-top: 5px;
        }
        .result-meta a, .preview-link {
            color: #1a0dab;
            text-decoration: none;
            margin-left: 10px;
            cursor: pointer;
        }
        .result-meta a:hover, .preview-link:hover {
            text-decoration: underline;
        }
        .file-icon {
            margin-right: 5px;
        }
        .pagination {
            text-align: center;
            margin: 30px 0;
        }
        .pagination button {
            background: #fff;
            border: 1px solid #ddd;
            padding: 8px 15px;
            margin: 0 3px;
            cursor: pointer;
            border-radius: 3px;
            transition: all 0.3s;
        }
        .pagination button.active {
            background-color: #5E2D9B;
            color: white;
            border-color: #5E2D9B;
        }
        .pagination button:hover:not(.active) {
            background-color: #f5f5f5;
        }
        .pagination-info {
            margin-top: 10px;
            color: #666;
            font-size: 14px;
            text-align: center;
        }
        .no-results {
            text-align: center;
            color: #666;
            padding: 30px 0;
            font-size: 16px;
        }
        .initial-message {
            text-align: center;
            color: #999;
            padding: 50px 0;
            font-size: 16px;
        }
        em {
            font-style: normal;
            background-color: #fff9c4;
            padding: 0 2px;
        }
        .loading {
            text-align: center;
            padding: 40px 0;
        }
        .recommendation {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            max-width: 750px;
            margin: 20px auto;
        }
        .recommendation h3 {
            font-size: 16px;
            color: #333;
            margin-top: 0;
            margin-bottom: 10px;
        }
        .recommendation-list {
            display: flex;
            flex-wrap: wrap;
        }
        .recommendation-item {
            margin-right: 10px;
            margin-bottom: 10px;
            background: #eee;
            border-radius: 16px;
            padding: 5px 12px;
            font-size: 13px;
            cursor: pointer;
            transition: all 0.3s;
        }
        .recommendation-item:hover {
            background: #ddd;
        }

    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <a href="/login" id="login-link">登录</a>
            <a href="/register" id="register-link">注册</a>
            <a href="/user/profile" id="profile-link" style="display:none;">个人中心</a>
            <a href="/logout" id="logout-link" style="display:none;">退出</a>
        </div>
        
        <div class="search-container">
            <div class="logo">
                <h1>南开大学搜索引擎</h1>
            </div>
            
            <div class="search-form-container">
                <div class="search-form">
                    <input type="text" id="search-input" class="search-input" placeholder="在南开大学资源中搜索..." autocomplete="off">
                    <button id="search-button" class="search-button">搜索</button>
                </div>
                <div class="history-container" id="history-container"></div>
                
                <div class="search-tabs">
                    <div class="search-option">
                        <input type="radio" id="type-all" name="search-type" value="all" checked>
                        <label for="type-all">全部</label>
                    </div>
                    <div class="search-option">
                        <input type="radio" id="type-web" name="search-type" value="web">
                        <label for="type-web">网页</label>
                    </div>
                    <div class="search-option">
                        <input type="radio" id="type-doc" name="search-type" value="doc">
                        <label for="type-doc">文档</label>
                    </div>
                    <div class="search-option">
                        <input type="radio" id="mode-normal" name="search-mode" value="normal" checked>
                        <label for="mode-normal">普通查询</label>
                    </div>
                    <div class="search-option">
                        <input type="radio" id="mode-phrase" name="search-mode" value="phrase">
                        <label for="mode-phrase">短语查询</label>
                    </div>
                    <div class="search-option">
                        <input type="radio" id="mode-wildcard" name="search-mode" value="wildcard">
                        <label for="mode-wildcard">通配查询</label>
                    </div>
                </div>
            </div>
        </div>
        
        <div id="recommendations" class="recommendation" style="display: none;">
            <div id="related-queries">
                <h3>相关搜索</h3>
                <div class="recommendation-list" id="related-list"></div>
            </div>
        </div>
        
        <div class="results-container" id="results">
            <div class="initial-message">
                请输入关键词开始搜索
            </div>
        </div>
        
        <div class="pagination" id="pagination">
            <!-- 分页将在这里显示 -->
        </div>
    </div>



    <script>
    // 全局变量
    let currentPage = 1;
    let totalResults = 0;
    let resultsPerPage = 10;
    let currentQuery = '';
    let currentType = 'all';
    let searchMode = 'normal';  
    
    // 转义HTML以防止XSS攻击
    function escapeHTML(str) {
        if (!str) return '';
        return str
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;');
    }
    
    // 全局分页函数 - 重新实现
    function goToPage(page) {
        if (!currentQuery) return;
        
        // 简单检查页码是否有效
        if (page < 1) return;
        
        // Elasticsearch限制，防止请求超出10000条结果
        const MAX_RESULTS = 10000;
        const maxPage = Math.floor(MAX_RESULTS / resultsPerPage);
        
        if (page > maxPage) {
            alert(`由于系统限制，最多只能查看前${maxPage}页结果。`);
            return;
        }
        
        // 执行搜索
        performSearch(currentQuery, currentType, page);
    }
    
    // 修复分页功能，恢复原来的按钮样式
    function updatePagination(total, currentPage, perPage) {
        // 计算总页数，考虑Elasticsearch的10000条结果限制
        const MAX_RESULTS = 10000;
        const totalPages = Math.min(Math.ceil(total / perPage), Math.floor(MAX_RESULTS / perPage));
        
        const paginationContainer = document.getElementById('pagination');
        
        if (totalPages <= 1) {
            paginationContainer.innerHTML = '';
            return;
        }
        
        let html = '';
        
        // 上一页按钮
        html += `<button ${currentPage === 1 ? 'disabled' : ''} onclick="goToPage(${currentPage - 1})">上一页</button>`;
        
        // 页码按钮
        const maxVisiblePages = 5;
        let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
        let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
        
        // 调整startPage以确保显示足够的页码
        if (endPage - startPage + 1 < maxVisiblePages) {
            startPage = Math.max(1, endPage - maxVisiblePages + 1);
        }
        
        if (startPage > 1) {
            html += `<button onclick="goToPage(1)">1</button>`;
            if (startPage > 2) {
                html += '<span>...</span>';
            }
        }
        
        for (let i = startPage; i <= endPage; i++) {
            html += `<button class="${i === currentPage ? 'active' : ''}" onclick="goToPage(${i})">${i}</button>`;
        }
        
        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                html += '<span>...</span>';
            }
            html += `<button onclick="goToPage(${totalPages})">${totalPages}</button>`;
        }
        
        // 下一页按钮
        html += `<button ${currentPage === totalPages ? 'disabled' : ''} onclick="goToPage(${currentPage + 1})">下一页</button>`;
        
        // 显示简单的结果计数
        html += `<div class="pagination-info">共 ${total} 条结果</div>`;
        
        paginationContainer.innerHTML = html;
    }

    // 显示搜索结果
    function displayResults(data) {
        const resultsContainer = document.getElementById('results');
        if (data.results.length === 0) {
            resultsContainer.innerHTML = '<div class="no-results">没有找到匹配的结果</div>';
            return;
        }
        
        let html = '';
        
        data.results.forEach(result => {
            let fileIcon = '';
            let fileInfo = '';
            
            // 对文档类型添加图标和文件信息
            if (result.type === 'document') {
                const fileType = result.file_type.toUpperCase();
                const fileSize = formatFileSize(result.file_size);
                fileIcon = getFileIcon(result.file_type);
                fileInfo = `<span class="file-type">${fileType}</span> · <span class="file-size">${fileSize}</span>`;
                
                // 确保标题中的引号被正确转义
                const safeTitle = result.title.replace(/'/g, "\\'").replace(/"/g, '\\"');
                const originalFilename = result.original_filename || result.title;
                
                html += `
                    <div class="result-item">
                        <div class="result-title">
                            ${fileIcon}
                            <a href="/view/document/${result.id}" target="_blank">${result.title}</a>
                        </div>
                        <div class="result-url">
                            ${result.original_filename ? `文件名: ${result.original_filename} · ` : ''}${result.domain || ''}
                        </div>
                        <div class="result-snippet">${result.snippet || ""}</div>
                        <div class="result-meta">
                            ${fileInfo}
                        </div>
                    </div>
                `;
            } else {
                html += `
                    <div class="result-item">
                        <div class="result-title">
                            <a href="${result.url}" target="_blank">${result.title}</a>
                        </div>
                        <div class="result-url">${result.url}</div>
                        <div class="result-snippet">${result.snippet}</div>
                        <div class="result-meta">
                            <a href="/snapshot/${result.page_hash}" target="_blank">网页快照</a>
                        </div>
                    </div>
                `;
            }
        });
        
        resultsContainer.innerHTML = html;
        
        // 更新分页
        updatePagination(data.total, data.page, data.per_page || 10);
    }

    // DOM加载完成后执行
    document.addEventListener('DOMContentLoaded', function() {
        const searchInput = document.getElementById('search-input');
        const searchButton = document.getElementById('search-button');
        const resultsContainer = document.getElementById('results');
        const paginationContainer = document.getElementById('pagination');
        const historyContainer = document.getElementById('history-container');
        const recommendationsContainer = document.getElementById('recommendations');
        const relatedList = document.getElementById('related-list');
        const personalizedList = document.getElementById('personalized-list');
        
        // 用户界面元素
        const profileLink = document.getElementById('profile-link');
        const loginLink = document.getElementById('login-link');
        const registerLink = document.getElementById('register-link');
        const logoutLink = document.getElementById('logout-link');
        
        // 检查用户登录状态
        checkLoginStatus();
        
        // 搜索模式选择
        document.querySelectorAll('input[name="search-type"]').forEach(radio => {
            radio.addEventListener('change', function() {
                currentType = this.value;
                if (currentQuery) {
                    performSearch(currentQuery, currentType, 1);
                }
            });
        });
        
        // 搜索模式选择
        document.querySelectorAll('input[name="search-mode"]').forEach(radio => {
            radio.addEventListener('change', function() {
                searchMode = this.value;
                if (currentQuery) {
                    performSearch(currentQuery, currentType, 1);
                }
            });
        });
        
        // 搜索按钮点击事件
        searchButton.addEventListener('click', function() {
            if (searchInput.value.trim()) {
                currentQuery = searchInput.value.trim();
                performSearch(currentQuery, currentType, 1);
            }
        });
        
        // 回车键搜索
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && searchInput.value.trim()) {
                currentQuery = searchInput.value.trim();
                performSearch(currentQuery, currentType, 1);
            }
        });
        
        // 搜索框获得焦点时显示历史记录
        searchInput.addEventListener('focus', function() {
            loadSearchHistory();
        });
        
        // 点击文档其他地方隐藏历史记录
        document.addEventListener('click', function(e) {
            if (!searchInput.contains(e.target) && !historyContainer.contains(e.target)) {
                historyContainer.style.display = 'none';
            }
        });
        
        // 检查URL参数，如果有搜索参数，执行搜索
        const urlParams = new URLSearchParams(window.location.search);
        const queryParam = urlParams.get('q');
        const pageParam = parseInt(urlParams.get('page')) || 1;
        const typeParam = urlParams.get('type') || 'all';

        if (queryParam) {
            document.getElementById('search-input').value = queryParam;
            currentQuery = queryParam;
            
            // 设置相应的搜索类型
            if (typeParam && document.getElementById(`type-${typeParam}`)) {
                document.getElementById(`type-${typeParam}`).checked = true;
                currentType = typeParam;
            }
            
            performSearch(queryParam, currentType, pageParam);
        }
    });
    
    function getFileIcon(fileType) {
        const icons = {
            'pdf': '📄',
            'doc': '📝',
            'docx': '📝',
            'xls': '📊',
            'xlsx': '📊',
            'ppt': '📽️',
            'pptx': '📽️',
            'zip': '🗜️',
            'rar': '🗜️'
        };
        return `<span class="file-icon">${icons[fileType.toLowerCase()] || '📄'}</span>`;
    }
    
    function formatFileSize(bytes) {
        if (bytes < 1024) return bytes + ' B';
        else if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
        else if (bytes < 1073741824) return (bytes / 1048576).toFixed(1) + ' MB';
        else return (bytes / 1073741824).toFixed(1) + ' GB';
    }
    
    function formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN');
    }
    


    // 执行搜索
    function performSearch(query, type, page) {
        const resultsContainer = document.getElementById('results');
        const paginationContainer = document.getElementById('pagination');
        
        resultsContainer.innerHTML = '<div class="loading">正在搜索，请稍候...</div>';
        paginationContainer.innerHTML = '';
        
        // 更新全局变量
        currentQuery = query;
        currentType = type;
        currentPage = page;
        
        // 构建API请求URL
        const url = `/api/search?q=${encodeURIComponent(query)}&type=${type}&page=${page}&size=${resultsPerPage}&search_mode=${searchMode}`;
        
        fetch(url)
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    if (!data.results || data.results.length === 0) {
                        // 没有结果
                        resultsContainer.innerHTML = '<div class="no-results">没有找到匹配的结果</div>';
                    } else {
                        // 显示结果
                        displayResults(data);
                    }
                    
                    // 更新分页
                    totalResults = data.total || 0;
                    updatePagination(totalResults, page, resultsPerPage);
                    
                    // 获取相关搜索
                    if (page === 1) {
                        try { getRelatedQueries(query); } catch(e) {}
                    }
                } else {
                    // 显示错误信息
                    resultsContainer.innerHTML = `<div class="no-results">搜索出错: ${data.message}</div>`;
                }
            })
            .catch(error => {
                resultsContainer.innerHTML = `<div class="no-results">搜索请求失败: ${error}</div>`;
            });
    }

    // 加载搜索历史
    function loadSearchHistory() {
        // 直接获取historyContainer元素
        const historyContainer = document.getElementById('history-container');
        
        fetch('/api/history')
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success' && data.history && data.history.length > 0) {
                    historyContainer.innerHTML = '';
                    
                    // 使用Set去重
                    const uniqueQueries = new Set();
                    const uniqueHistory = [];
                    
                    data.history.forEach(item => {
                        if (!uniqueQueries.has(item.query)) {
                            uniqueQueries.add(item.query);
                            uniqueHistory.push(item);
                        }
                    });
                    
                    uniqueHistory.forEach(item => {
                        const div = document.createElement('div');
                        div.className = 'history-item';
                        div.textContent = item.query;
                        
                        div.addEventListener('click', function() {
                            const searchInput = document.getElementById('search-input');
                            searchInput.value = item.query;
                            currentQuery = item.query;
                            historyContainer.style.display = 'none';
                            performSearch(item.query, currentType, 1);
                        });
                        
                        historyContainer.appendChild(div);
                    });
                    
                    historyContainer.style.display = 'block';
                } else {
                    historyContainer.style.display = 'none';
                }
            })
            .catch(error => {
                console.error('加载历史记录失败:', error);
                historyContainer.style.display = 'none';
            });
    }

    // 检查登录状态
    function checkLoginStatus() {
        // 从cookie获取会话信息
        const cookies = document.cookie.split(';').reduce((acc, cookie) => {
            const [key, value] = cookie.trim().split('=');
            acc[key] = value;
            return acc;
        }, {});
        
        // 获取DOM元素
        const profileLink = document.getElementById('profile-link');
        const loginLink = document.getElementById('login-link');
        const registerLink = document.getElementById('register-link');
        const logoutLink = document.getElementById('logout-link');
        
        // 检查是否已登录
        if ('username' in sessionStorage) {
            // 已登录状态
            profileLink.style.display = 'inline';
            logoutLink.style.display = 'inline';
            loginLink.style.display = 'none';
            registerLink.style.display = 'none';
        } else {
            // 未登录状态
            profileLink.style.display = 'none';
            logoutLink.style.display = 'none';
            loginLink.style.display = 'inline';
            registerLink.style.display = 'inline';
        }
    }

    // 获取相关搜索
    function getRelatedQueries(query) {
        const recommendations = document.getElementById('recommendations');
        const relatedList = document.getElementById('related-list');
        
        if (!recommendations || !relatedList) return;
        
        fetch(`/api/recommend?q=${encodeURIComponent(query)}`)
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    // 显示相关查询
                    relatedList.innerHTML = '';
                    if (data.related_terms && data.related_terms.length > 0) {
                        data.related_terms.forEach(term => {
                            const div = document.createElement('div');
                            div.className = 'recommendation-item';
                            div.textContent = term;
                            div.addEventListener('click', () => {
                                document.getElementById('search-input').value = term;
                                currentQuery = term;
                                performSearch(term, currentType, 1);
                            });
                            relatedList.appendChild(div);
                        });
                        
                        recommendations.style.display = 'block';
                    } else {
                        recommendations.style.display = 'none';
                    }
                }
            })
            .catch(error => {
                console.error('获取相关搜索失败:', error);
                if (recommendations) recommendations.style.display = 'none';
            });
    }
    </script>
</body>
</html>